<?php


namespace app\chat\server;
use app\chat\model\Message;
use app\chat\model\Order as OrderModel;
use app\chat\model\ChatUser as ChatUserModel;
use app\chat\model\FenPei as FenPeiModel;

/**
 * 服务层
 */
class Chat
{
    /**
     * 获取历史会话 | 渲染左边第一列
     * 不同角色获取的数据不一样
     */
    public static function  getConversation(){
        // 定义返回数据
        $data = [
          [
              'codeId'   => '',  // 群、用户ID
              'username' => '',  // 用户账号
              'name'     => '',  // 群名、用户姓名
              'head'     => '',  // 头像
              'end_msg'  => '',  // 最后一次的聊天内容
              'msg_time'  => '',  // 最后一次的聊天的时间
              'type'     => '',  // 聊天类型 friend 单聊  group 群聊
              'orderId'  => '',  // 订单ID
          ]
        ];
        switch (getrole()){
            case EMPLOYER:
                // 获取雇主的历史会话
                return self::getEMPLOYERHConversation();
                break;
            case ADMIN:
                return self::getADMINConversation();
            case HOUSEKEEPER:
                return self::getHOUSEKEEPERConversation();
                break;
            case DEVELOPER:
                return self::getDEVELOPERConversation();

        }
    }

    // 开发者 - 聊天历史
    public static function getDEVELOPERConversation(){
        $msg = Message::where('js_userid','=',session('user.id'))->order('id','asc')->select();
        if (empty($msg)){
            return [];
        }
        $data = [];
        foreach ($msg as $value){
            $data[] = [
                'id' => $value['id'],
                'code' => $value['code'],
                'js_userid' => $value['js_userid'],
                'send_uid' => $value['send_uid'],
                'send_message' => $value['send_message'],
                'message_type' => $value['message_type'],
                'insetrt_time' => $value['insetrt_time'],
                'type' => $value['type'],
            ];
        }
        $data = assoc_unique($data,'code');
        $time1 = [];
        foreach ($data as $usertime){
            $username = self::getUserNameInfo($usertime['send_uid']);
            $code = getCode($usertime['send_uid']);
            $msg = Message::where(['code'=>$code])
                ->where(['type'=>'friend'])
                ->field('id,send_message,insetrt_time,type')
                ->order('id','desc')
                ->find();
            // 获取最后一条数据
            $time1[] = [
                'codeId'   => $username['id'],
                'username' => $username['username'],
                'name'     => $username['name'],
                'head'     => $username['head'],
                'end_msg'  => $msg['send_message'],
                'msg_time' => $msg['insetrt_time'],
                'type'     => $msg['type'],
                'orderId'  => '', // 多个订单的问题
                'code'     => $usertime['code']
            ];
        }

        $msg = Message::where('send_uid','=',session('user.id'))->order('insetrt_time','asc')->select();
        $data = [];
        foreach ($msg as $value){
            $data[] = [
                'id' => $value['id'],
                'code' => $value['code'],
                'js_userid' => $value['js_userid'],
                'send_uid' => $value['send_uid'],
                'send_message' => $value['send_message'],
                'message_type' => $value['message_type'],
                'insetrt_time' => $value['insetrt_time'],
                'type' => $value['type'],
            ];
        }
        $data = assoc_unique($data,'code');
        $time = [];
        foreach ($data as $usertime){
            $username = self::getUserNameInfo($usertime['js_userid']);
            $code = getCode($usertime['js_userid']);
            $msg = Message::where(['code'=>$code])
                ->where(['type'=>'friend'])
                ->field('id,send_message,insetrt_time,type')
                ->order('id','desc')
                ->find();
            // 获取最后一条数据
            $time[] = [
                'codeId'   => $username['id'],
                'username' => $username['username'],
                'name'     => $username['name'],
                'head'     => $username['head'],
                'end_msg'  => $msg['send_message'],
                'msg_time' => $msg['insetrt_time'],
                'type'     => $msg['type'],
                'orderId'  => '', // 多个订单的问题
                'code'     => $usertime['code']
            ];
        }
        $time = array_reverse($time);
        $data = array_merge($time,$time1);
        $data = assoc_unique($data,'code');
        return $data;
    }

    // 管家 -聊天历史
    public static function getHOUSEKEEPERConversation(){
        $msg = Message::where('js_userid','=',session('user.id'))->order('id','asc')->select();
        if (empty($msg)){
            return [];
        }
        $data = [];
        foreach ($msg as $value){
            $data[] = [
                'id' => $value['id'],
                'code' => $value['code'],
                'js_userid' => $value['js_userid'],
                'send_uid' => $value['send_uid'],
                'send_message' => $value['send_message'],
                'message_type' => $value['message_type'],
                'insetrt_time' => $value['insetrt_time'],
                'type' => $value['type'],
            ];
        }
        $data = assoc_unique($data,'code');
        $time1 = [];
        foreach ($data as $usertime){
            $username = self::getUserNameInfo($usertime['send_uid']);
            $code = getCode($usertime['send_uid']);
            $msg = Message::where(['code'=>$code])
                ->where(['type'=>'friend'])
                ->field('id,send_message,insetrt_time,type')
                ->order('id','desc')
                ->find();
            // 获取最后一条数据
            $time1[] = [
                'codeId'   => $username['id'],
                'username' => $username['username'],
                'name'     => $username['name'],
                'head'     => $username['head'],
                'end_msg'  => $msg['send_message'],
                'msg_time' => $msg['insetrt_time'],
                'type'     => $msg['type'],
                'orderId'  => '', // 多个订单的问题
                'code'     => $usertime['code']
            ];
        }

        $msg = Message::where('send_uid','=',session('user.id'))->order('insetrt_time','asc')->select();
        $data = [];
        foreach ($msg as $value){
            $data[] = [
                'id' => $value['id'],
                'code' => $value['code'],
                'js_userid' => $value['js_userid'],
                'send_uid' => $value['send_uid'],
                'send_message' => $value['send_message'],
                'message_type' => $value['message_type'],
                'insetrt_time' => $value['insetrt_time'],
                'type' => $value['type'],
            ];
        }
        $data = assoc_unique($data,'code');
        $time = [];
        foreach ($data as $usertime){
            $username = self::getUserNameInfo($usertime['js_userid']);
            $code = getCode($usertime['js_userid']);
            $msg = Message::where(['code'=>$code])
                ->where(['type'=>'friend'])
                ->field('id,send_message,insetrt_time,type')
                ->order('id','desc')
                ->find();
            // 获取最后一条数据
            $time[] = [
                'codeId'   => $username['id'],
                'username' => $username['username'],
                'name'     => $username['name'],
                'head'     => $username['head'],
                'end_msg'  => $msg['send_message'],
                'msg_time' => $msg['insetrt_time'],
                'type'     => $msg['type'],
                'orderId'  => '', // 多个订单的问题
                'code'     => $usertime['code']
            ];
        }
        $time = array_reverse($time);
        $data = array_merge($time,$time1);
        $data = assoc_unique($data,'code');
        return $data;
    }

    // 获取好友列表
    public static function getGoodfriendlist(){
        switch (getrole()){
            case EMPLOYER:
                // 获取雇主的好友
                return[];
                break;
            case ADMIN:
                // 获取管理员的好友
//                根据用户组
                $data = [
                    'admin'   => [],
                    'guzhu'   => [],
                    'guanjia' => [],
                    'kaifaz'  => []
                ];

                $user = ChatUserModel::where('id','<>',session('user.id'))->where(['state'=>1])->select();
                foreach ($user as $value){
                    if ($value['group_id'] == 1){
                        $data['admin'][] = $value;
                    }else if ($value['group_id'] == 2){
                        $data['guanjia'][] = $value;
                    }else if ($value['group_id'] == 5){
                        $data['guzhu'][] = $value;
                    }else if ($value['group_id'] == 6){
                        $data['kaifaz'][] = $value;
                    }
                }
                $return = [
                  [
                      'name' => '管理员',
                      'data' => $data['admin']
                  ], [
                        'name' => '管家',
                        'data' => $data['guanjia']
                    ],
                     [
                     'name' => '开发者',
                    'data' => $data['kaifaz']
                ],
                    [
                        'name' => '客户',
                        'data' => $data['guzhu']
                    ]
                ];
                return $return;
                break;
            case HOUSEKEEPER :
                $data = [
                    'admin'   => [],
                    'guzhu'   => [],
                    'kaifaz'  => []
                ];
                $fenpei = FenPeiModel::where('guan_jia_id','=',session('user.id'))
                    ->select();

                // 提取用户信息
                $user = [];
                foreach ($fenpei as $value){
                    $user[] = $value['admin_id'];
                    $user[] = $value['user_id'];
                    $user[] = $value['kai_fa_id'];
                }
                $userid = array_unique($user);
                $userInfo = ChatUserModel::where('id','in',$userid)->where(['state'=>1])->select();
                foreach ($userInfo as $value){
                    if ($value['group_id'] == 1){
                        $data['admin'][] = $value;
                    }else if ($value['group_id'] == 5){
                        $data['guzhu'][] = $value;
                    }else if ($value['group_id'] == 6){
                        $data['kaifaz'][] = $value;
                    }
                }
                $return = [
                    [
                        'name' => '管理员',
                        'data' => $data['admin']
                    ],
                    [
                        'name' => '开发者',
                        'data' => $data['kaifaz']
                    ],
                    [
                        'name' => '客户',
                        'data' => $data['guzhu']
                    ]
                ];
                return $return;
                break;
            case DEVELOPER:
                $data = [
                    'admin'   => [],
                    'guzhu'   => [],
                    'guanjia' => [],
                ];

                $fenpei = FenPeiModel::where('kai_fa_id','=',session('user.id'))
                    ->select();

                // 提取用户信息
                $user = [];
                foreach ($fenpei as $value){
                    $user[] = $value['admin_id'];
                    $user[] = $value['user_id'];
                    $user[] = $value['guan_jia_id'];
                }
                $userid = array_unique($user);
                $userInfo = ChatUserModel::where('id','in',$userid)->where(['state'=>1])->select();

                foreach ($userInfo as $value){
                    if ($value['group_id'] == 1){
                        $data['admin'][] = $value;
                    }else if ($value['group_id'] == 2){
                        $data['guanjia'][] = $value;
                    }else if ($value['group_id'] == 5){
                        $data['guzhu'][] = $value;
                    }
                }
                $return = [
                    [
                        'name' => '管理员',
                        'data' => $data['admin']
                    ], [
                        'name' => '管家',
                        'data' => $data['guanjia']
                    ],
                    [
                        'name' => '客户',
                        'data' => $data['guzhu']
                    ]
                ];
                return $return;
                break;

        }
    }

    /**
     * 获取历史会话 | 渲染左边第一列
     * 不同角色获取的数据不一样
     * 获取雇主的历史会话
     */
    public static function getEMPLOYERHConversation(){
        // 获取分配 单聊
        $fenpei = FenPeiModel::where(['user_id'=>session('user.id')])
            ->select();

        $data = [];
        $return = [];
        foreach ($fenpei as $value){
            // 把用户
            if (!empty($value['admin_id'])){
                $data[] = $value['admin_id'];
            }
            if (!empty($value['admin_id'])){
                $data[] = $value['guan_jia_id'];
            }
            if (!empty($value['admin_id'])){
                $data[] = $value['kai_fa_id'];
            }
            $user = ChatUserModel::where('id','in',$data)
                ->where(['state'=>1])
                ->select();

            $time = [];
            foreach ($user as $usertime){
                // 获取最后一条数据
                $code = getCode($usertime['id']);
                $msg = Message::where(['code'=>$code])
                    ->where(['type'=>'friend'])
                    ->field('id,send_message,insetrt_time,type')
                    ->order('id','desc')
                    ->find();
//                dd($msg);
                $time[] = [
                    'codeId'   => $usertime['id'],
                    'username' => $usertime['username'],
                    'name'     => $usertime['name'],
                    'head'     => $usertime['head'],
                    'end_msg'  => $msg['send_message'],
                    'msg_time' => $msg['insetrt_time'],
                    'type'     => $msg['type'],
                    'orderId'  => $value['order_id'] // 多个订单的问题
                ];
            }
            $return = array_merge($return,$time);
        }
        $return = assoc_unique($return,'codeId');
        $return = array_reverse($return,true);
        sort($return);
//        dd($return);
        return $return;
    }

    // 获取管理员的历史信息
    public static function getADMINConversation(){
        $msg = Message::where('js_userid','=',session('user.id'))->order('id','asc')->select();
        if (empty($msg)){
            return [];
        }
        $data = [];
        foreach ($msg as $value){
            $data[] = [
                'id' => $value['id'],
                'code' => $value['code'],
                'js_userid' => $value['js_userid'],
                'send_uid' => $value['send_uid'],
                'send_message' => $value['send_message'],
                'message_type' => $value['message_type'],
                'insetrt_time' => $value['insetrt_time'],
                'type' => $value['type'],
            ];
        }
        $data = assoc_unique($data,'code');
        $time1 = [];
        foreach ($data as $usertime){
            $username = self::getUserNameInfo($usertime['send_uid']);
            $code = getCode($usertime['send_uid']);
            $msg = Message::where(['code'=>$code])
                ->where(['type'=>'friend'])
                ->field('id,send_message,insetrt_time,type')
                ->order('id','desc')
                ->find();
            // 获取最后一条数据
            $time1[] = [
                'codeId'   => $username['id'],
                'username' => $username['username'],
                'name'     => $username['name'],
                'head'     => $username['head'],
                'end_msg'  => $msg['send_message'],
                'msg_time' => $msg['insetrt_time'],
                'type'     => $msg['type'],
                'orderId'  => '', // 多个订单的问题
                'code'     => $usertime['code']
            ];
        }

        $msg = Message::where('send_uid','=',session('user.id'))->order('insetrt_time','asc')->select();
        $data = [];
        foreach ($msg as $value){
            $data[] = [
                'id' => $value['id'],
                'code' => $value['code'],
                'js_userid' => $value['js_userid'],
                'send_uid' => $value['send_uid'],
                'send_message' => $value['send_message'],
                'message_type' => $value['message_type'],
                'insetrt_time' => $value['insetrt_time'],
                'type' => $value['type'],
            ];
        }
        $data = assoc_unique($data,'code');
        $time = [];
        foreach ($data as $usertime){
            $username = self::getUserNameInfo($usertime['js_userid']);
            $code = getCode($usertime['js_userid']);
            $msg = Message::where(['code'=>$code])
                ->where(['type'=>'friend'])
                ->field('id,send_message,insetrt_time,type')
                ->order('id','desc')
                ->find();
            // 获取最后一条数据
            $time[] = [
                'codeId'   => $username['id'],
                'username' => $username['username'],
                'name'     => $username['name'],
                'head'     => $username['head'],
                'end_msg'  => $msg['send_message'],
                'msg_time' => $msg['insetrt_time'],
                'type'     => $msg['type'],
                'orderId'  => '', // 多个订单的问题
                'code'     => $usertime['code']
            ];
        }
        $time = array_reverse($time);
        $data = array_merge($time,$time1);
        $data = assoc_unique($data,'code');
        return $data;
    }

    // 发送消息
    public static function sedMsg($post){
        $return = [
            'state' => 'error',
            'msg'  => '',
            'data' => ''
        ];
        if (empty($post) || empty($post['type']) || empty($post['codeid'])) {
            $return['msg'] = '发送参数错误';
            return $return;
        }

        // 查询是否存在  单聊
        if ($post['type'] == 'friend'){
            $user = ChatUserModel::get($post['codeid']);
            if (empty($user)){
                $return['msg'] = '发送用户不存在';
                return json($return);
            }

            // 入库 单聊得到会话ID
            $data = [
                'code'      => getCode($post['codeid']),
                'js_userid' => $post['codeid'],
                'send_uid'  => session('user.id'),
                'send_message' => $post['content'],
                'message_type' => 0,
                'insetrt_time' => date('H:i:s'),
                'type'         => $post['type']
            ];

            $msg = Message::create($data);
            if (empty($msg)){
                $return['msg'] = '发送失败';
                return $return;
            }
            $data['mid'] = $msg['id'];
            $data['head'] = $post['head'];
            $user =  self::getUserNameInfo($data['js_userid']);
            $data['name'] = $user['name'];
            $data['jsname'] = $user['head'];
            $return['state'] = 'success';
            $return['msg']   = '发送成功';
            $return['data']  = $data;
            return $return;
        }else if ($post['type'] == 'g'){ // 群聊

        }

    }

    // 获取消息
    public static function getMsg($post){
        $return = [
            'state' => 'error',
            'msg'  => '',
            'data' => ''
        ];
        if (empty($post) || empty($post['type']) || empty($post['codeid'])) {
            $return['msg'] = '发送参数错误';
            return $return;
        }

        if ($post['type'] == 'friend'){ // 单聊
            // 获取会话标识
            $code = getCode($post['codeid']);
            $msg = Message::where(['code'=>$code])
                ->where(['type'=>'friend'])
                ->order('id','desc')
//                ->order('insetrt_time','desc')
                ->field('id,send_message,insetrt_time,type,send_uid')
                ->limit('20')
                ->select();
            if (empty($msg)){
                $return['state'] = 'success';
                $return['msg']   = '获取成功';
                $return['data']  = [];
                return $return;
            }
            $msgList = [];
            foreach ($msg as $value){
                $mine = '';
                $username = '';
                $avatar = '';
                $id = '';
                $fromid = '';

                if ($value['send_uid'] != session('user.id')){
                    $UserNameInfo = self::getUserNameInfo($post['codeid']);
                    $username = $UserNameInfo['name'];
                    $avatar = $UserNameInfo['head'];
                    $mine = false;
                }else{
                    $UserNameInfo = self::getUserNameInfo(session('user.id'));
                    $username = $UserNameInfo['name'];
                    $avatar = $UserNameInfo['head'];
                    $mine = true;
                }

                $msgList[] = [
                    'cid'           => $value['id'],  // 会话ID
//                    'code'          => $value['code'], // 会话标识
//                    'js_userid'     => $value['js_userid'], // 接受人
//                    'send_uid'      => $value['send_uid'], // 发送人
                    'message'       => $value['send_message'], // 内容
//                    'message_type'  => $value['message_type'], // 消息类型
                    'insetrt_time'  => $value['insetrt_time'], // 发送时间
                    'type'          => $value['type'], // 聊天类型
                    'mine'          => $mine, //是否我发送的消息
                    'avatar'        => $avatar, //消息来源用户头像
                    'username'      => $username, //消息来源用户名
                ];
            }
            $msgList = array_reverse($msgList);
            $return['state'] = 'success';
            $return['msg']   = '获取成功';
            $return['data']  = $msgList;
            return $return;
        }
    }

    // 根据用户ID 获取用户信息
    public  static function getUserNameInfo($uid){
        if (empty($uid)){
            return [];
        }
        return ChatUserModel::where(['id'=>$uid])->field('id,username,name,head')->find();
    }
}